<?php
require_once('../../../wp-load.php');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    wp_send_json_error('Invalid request method');
}

$data = json_decode(file_get_contents('php://input'), true);
$message = sanitize_text_field($data['message'] ?? '');

if (empty($message)) {
    wp_send_json_error('Message is required');
}

// 读取本地知识库
$knowledge_path = __DIR__ . '/knowledge.json';
$knowledge = json_decode(file_get_contents($knowledge_path), true);

// 构建系统提示信息，包含所有知识库信息
$system_prompt = "你是{$knowledge['role']}。{$knowledge['description']}。\n\n";
$system_prompt .= "关于我的信息：\n";
$system_prompt .= "- {$knowledge['info']['about']}\n";
$system_prompt .= "- 网站：{$knowledge['info']['contacts']['website']}\n";
$system_prompt .= "- 微信：{$knowledge['info']['contacts']['wechat']}\n";
$system_prompt .= "- 小红书：{$knowledge['info']['contacts']['xiaohongshu']}\n";
$system_prompt .= "- 课程平台：{$knowledge['info']['course']['platform']}\n";
$system_prompt .= "- 课程链接：{$knowledge['info']['course']['url']}\n\n";

// 添加FAQ信息作为背景知识
$system_prompt .= "常见问题解答：\n";
foreach ($knowledge['faq'] as $qa) {
    $system_prompt .= "Q: {$qa['question']}\nA: {$qa['answer']}\n\n";
}

$system_prompt .= "\n请根据以上信息，准确、专业地回答用户问题。如果问题与课程或者网站无关，请以AI助手的身份提供帮助。";

// 调用AI API
$api_key = 'sk-4b3a5511386e442582fa6d37b758b82e';
$url = 'https://api.deepseek.com/v1/chat/completions';

$response = wp_remote_post($url, array(
    'headers' => array(
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type' => 'application/json'
    ),
    'body' => json_encode(array(
        'model' => 'deepseek-chat',
        'messages' => array(
            array('role' => 'system', 'content' => $system_prompt),
            array('role' => 'user', 'content' => $message)
        ),
        'temperature' => 0.7, // 添加温度参数，使回答更自然
        'max_tokens' => 1000  // 限制回答长度
    ))
));

if (is_wp_error($response)) {
    wp_send_json_error($response->get_error_message());
}

$body = json_decode(wp_remote_retrieve_body($response), true);
wp_send_json_success($body['choices'][0]['message']['content']); 